<template>
    <div id="comm">

        <Head></Head>
        <div id="community" v-loading="isLoading">

            <h2>🎓 学习交流社区</h2>

            <!-- 发布帖子 -->
            <div class="post-form">
                <input v-model="newPost.title" type="text" placeholder="请输入标题" />
                <textarea v-model="newPost.content" rows="4" placeholder="分享你的学习心得..."></textarea>
                <input type="file" class="file-upload" @change="handleFileUpload" />
                <button @click="submitPost">🚀 发布帖子</button>
            </div>

            <!-- 帖子列表 -->
            <div class="post-list" v-if="posts.length">
                <div v-for="(post, index) in posts" :key="index" class="post-item">
                    <div class="post-header">
                        <img :src="post.avatar" alt="头像" class="avatar" @click="goToChat(post.username, post.userId)" />
                        <div class="user-info">
                            <span class="username">{{ post.username }}</span>
                            <span class="timestamp">{{ post.createTime }}</span>
                        </div>
                        <!-- 删除按钮：只允许自己删除 -->
                        <button v-if="post.username === username" class="delete-btn"
                            @click="deletePost(post.id, index)">🗑 删除</button>
                    </div>
                    <h3>{{ post.title }}</h3>
                    <p class="content">{{ post.content }}</p>

                    <!-- 图片预览或附件链接 -->
                    <div v-if="post.fileUrl" class="file-preview">
                        <img v-if="isImage(post.fileUrl)" :src="post.fileUrl" alt="附件预览" class="preview-image" />
                        <a v-else :href="post.fileUrl" target="_blank">📎 点击下载附件</a>
                    </div>

                    <div class="actions">
                        <button @click="likePost(post)">👍 {{ post.likes }}</button>
                        <button @click="sharePost(post)">🔄 {{ post.shares }}</button>
                        <button @click="commentPost(post)">💬 {{ post.comments }}</button>
                    </div>
                </div>
            </div>
            <p v-else>暂无帖子，快来发布第一条吧！</p>
        </div>
    </div>

</template>

<script>
import axios from 'axios';
import Head from "../../components/head.vue";


export default {
    name: "Community",
    components: { Head },
    data() {
        return {
            newPost: {
                title: "",
                content: "",
                file: null
            },
            isLoading: false,
            username: localStorage.getItem("username"), // 模拟用户名（实际应通过登录信息获取）
            posts: [],
            currentUser: "studentA" // 模拟当前用户（实际应通过登录信息获取）
        };
    },
    methods: {
        handleFileUpload(event) {
            this.newPost.file = event.target.files[0];
        },
        isImage(url) {
            return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
        },
        async submitPost() {
            if (!this.newPost.title || !this.newPost.content) {
                this.$message.error("获取帖子失败，请稍后重试！");

                return;
            }

            const formData = new FormData();
            formData.append("title", this.newPost.title);
            formData.append("content", this.newPost.content);
            if (this.newPost.file) {
                formData.append("file", this.newPost.file);
            }

            try {
                const response = await this.$http.post('/api/community/add', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });

                if (response.data.code === 200) {
                    const post = response.data.data;
                    this.fetchPosts(); // 刷新帖子列表
                    this.posts.unshift(post);
                    this.newPost = { title: "", content: "", file: null };
                    this.$message.success("发布成功！");
                } else {
                    this.$message.error("发布失败：" + response.data.msg);
                }
            } catch (error) {
                console.error(error);
                this.$message.error("获取帖子失败，请稍后重试！");

            }
        },
        async fetchPosts() {
            this.isLoading = true;
            try {
                const response = await this.$http.get('/api/resources-community/all');
                if (response.data.code === 200) {
                    this.isLoading = false;
                    this.posts = response.data.data.map(post => ({
                        ...post,
                        createTime: new Date(post.createTime).toLocaleString(),
                        avatar: "http://localhost:8585/uploads/" + post.avatar,
                        fileUrl: post.fileUrl ? "http://localhost:8585/avatar/" + post.fileUrl : ""
                    }));
                    // 翻转帖子顺序
                    this.posts.reverse();
                } else {
                    this.$message.error("获取帖子失败，请稍后重试！");

                }
            } catch (error) {
                console.error(error);
                this.$message.error("获取帖子失败，请稍后重试！");
            }
        },
        async deletePost(postId, index) {
            this.$confirm("确定要删除该帖子吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                // 用户确认删除后再发请求
                try {
                    const res = await this.$http.delete(`/api/resources-community/delete/${postId}`);
                    if (res.data.code === 200) {
                        this.$message.success("删除成功！");
                        this.fetchPosts(); // 刷新帖子列表
                    } else {
                        this.$message.error("删除失败：" + res.data.msg);
                    }
                } catch (err) {
                    console.error(err);
                    this.$message.error("删除失败，请稍后重试！");
                }
            }).catch(() => {
                // 用户点击“取消”
                this.$message.info("已取消删除");
            });
        },
        goToChat(targetUsername, userId) {
            if (targetUsername === this.username) {
                this.$message.info("不能和自己聊天哦！");
                return;
            }
            // 修改为使用 'username' 作为参数名称，确保和其他部分保持一致
            this.$router.push(
                {
                    name: 'Chat',
                    params: { username: targetUsername },

                    params: { userId: userId },
                    query: {
                        username: targetUsername,
                        userId: userId
                    }
                }
            );
        },

        likePost(post) {
            post.likes++;
        },
        sharePost(post) {
            post.shares++;
        },
        commentPost(post) {
            post.comments++;
        }
    },
    mounted() {
        this.fetchPosts();
    }
};
</script>

<style scoped lang="less">
#community {
    padding: 30px;
    max-width: 900px;
    margin: auto;
    background: #f0f4f8;
    border-radius: 10px;
    font-family: 'Segoe UI', sans-serif;
}

h2 {
    text-align: center;
    color: #333;
    margin-bottom: 25px;
}

.post-form {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.06);
    margin-bottom: 30px;
}

.post-form input[type="text"],
.post-form textarea {
    width: 100%;
    padding: 10px;
    font-size: 15px;
    border-radius: 6px;
    border: 1px solid #ccc;
    margin-bottom: 10px;
}

.file-upload {
    margin-bottom: 15px;
}

button {
    background: linear-gradient(to right, #4facfe, #00f2fe);
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-weight: bold;
    transition: background 0.3s ease;
}

button:hover {
    background: linear-gradient(to right, #00c6ff, #0072ff);
}

.post-list .post-item {
    background: white;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 15px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
    position: relative;
}

.post-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.user-info {
    display: flex;
    flex-direction: column;
}

.username {
    font-weight: bold;
    color: #333;
}

.timestamp {
    color: #888;
    font-size: 12px;
}

.content {
    color: #555;
    margin-bottom: 10px;
}

.file-preview {
    margin-bottom: 10px;
}

.preview-image {
    max-width: 100%;
    border-radius: 6px;
}

.file-preview a {
    color: #1a73e8;
    text-decoration: none;
    font-size: 14px;
}

.actions {
    display: flex;
    gap: 15px;
    margin-top: 10px;
}

.actions button {
    background: none;
    border: 1px solid #ddd;
    padding: 6px 15px;
    border-radius: 6px;
    color: #409eff;
    cursor: pointer;
}

.actions button:hover {
    background-color: #f0f5ff;
}

.delete-btn {
    position: absolute;
    right: 20px;
    top: 15px;
    background: #ff4d4f;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 6px;
    cursor: pointer;
}

.delete-btn:hover {
    background: #ff7875;
}

/deep/ .head_center {
    display: none;
}

/deep/ .header {
    height: 50px;
}
</style>